<?php
namespace app\index\controller;

use app\common\model\UserDownloadCount;
use app\common\model\WebSiteCookie;
use think\facade\Cache;

class Job
{
    public function index()
    {
        $this->refresh_count();
        $this->refresh_cookie();
        return show_success('刷新成功');
    }

    private function refresh_count()
    {
        UserDownloadCount::where('day_refresh_time', '<>', date('Ymd'))->chunk(100, function ($count_list) {
            $count_list->update([
                'day_refresh_time' => date('Ymd'),
                'day_used_time'    => 0,
            ]);
        });
        UserDownloadCount::where('week_refresh_time', '<>', date('W'))->chunk(100, function ($count_list) {
            $count_list->update([
                'week_refresh_time' => date('W'),
                'week_used_time'    => 0,
            ]);
        });
        UserDownloadCount::where('month_refresh_time', '<>', date('Ym'))->chunk(100, function ($count_list) {
            $count_list->update([
                'month_refresh_time' => date('Ym'),
                'month_used_time'    => 0,
            ]);
        });
        UserDownloadCount::where('year_refresh_time', '<>', date('Y'))->chunk(100, function ($count_list) {
            $count_list->update([
                'year_refresh_time' => date('Y'),
                'year_used_time'    => 0,
            ]);
        });
    }

    private function refresh_cookie()
    {

        $refresh_cookie_time = Cache::get('refresh_cookie_time');
        $now                 = date('Y-m-d');
        if (empty($refresh_cookie_time) || $refresh_cookie_time != $now) {
            WebSiteCookie::chunk(100, function ($cookies) {
                $cookies->update(['day_used' => 0]);
            });
            Cache::set('refresh_cookie_time', $now);
        }
    }
}
